<template>
  <div class="my-team-container">
    <!-- 标签页 -->
    <a-tabs v-model:value="activeTab" @change="onTabChange">
      <a-tab-pane key="created" tab="我创建/管理的战队">
        <a-list :data-source="createdTeams" :loading="loading" bordered :locale="{ emptyText: '暂无创建的战队' }">
          <template #renderItem="{ item }">
            <a-list-item style="display:flex; justify-content:space-between; align-items:center; cursor:pointer;"
              @click="openDetail(item)">
              <div style="flex:1;">
                <a-list-item-meta :title="item.teamName" :description="item.description || '暂无描述'" />
              </div>
            </a-list-item>
          </template>
        </a-list>
      </a-tab-pane>

      <a-tab-pane key="joined" tab="我加入的战队">
        <a-list :data-source="joinedTeams" :loading="loading" bordered :locale="{ emptyText: '暂无加入的战队' }">
          <template #renderItem="{ item }">
            <a-list-item style="display:flex; justify-content:space-between; align-items:center; cursor:pointer;"
              @click="openDetail(item)">
              <div style="flex:1;">
                <a-list-item-meta :title="item.teamName" :description="item.description || '暂无描述'" />
              </div>
            </a-list-item>
          </template>
        </a-list>
      </a-tab-pane>

      <a-tab-pane key="subscribed" tab="我订阅的战队">
        <a-list :data-source="subscribedTeams" :loading="loading" bordered :locale="{ emptyText: '暂无订阅的战队' }">
          <template #renderItem="{ item }">
            <a-list-item style="display:flex; justify-content:space-between; align-items:center;">
              <div style="flex:1; cursor:pointer;" @click="openDetail(item)">
                <a-list-item-meta :title="item.teamName" :description="item.description || '暂无描述'" />
              </div>
            </a-list-item>
          </template>
        </a-list>
      </a-tab-pane>
    </a-tabs>

    <!-- 战队详情弹窗 -->
    <a-modal v-model:visible="detailVisible" :title="selectedTeam?.teamName || '战队详情'" width="720" @cancel="closeDetail"
      :footer="null" :forceRender="true">
      <div v-if="selectedTeam">
        <!-- 战队详情部分 -->
        <div class="team-detail">
          <a-spin :spinning="detailLoading">
            <div v-if="!editing">
              <a-descriptions bordered :column="2">
                <a-descriptions-item label="战队名称">{{ selectedTeam.teamName }}</a-descriptions-item>
                <a-descriptions-item label="创建时间">{{ formatDate(selectedTeam.createTime) }}</a-descriptions-item>
                <a-descriptions-item label="战队描述" :span="2">{{ selectedTeam.description || '暂无描述'
                }}</a-descriptions-item>
                <a-descriptions-item label="标签">{{ selectedTeam.tag || '无' }}</a-descriptions-item>
                <a-descriptions-item label="最大成员数">{{ selectedTeam.maxCount ?? '无限制' }}</a-descriptions-item>
                <!-- 添加订阅相关字段 -->
                <a-descriptions-item label="订阅价格"
                  v-if="selectedTeam.subscribePrice && selectedTeam.subscribeCycle !== 0">
                  ¥{{ selectedTeam.subscribePrice }} / {{ formatCycle(selectedTeam.subscribeCycle) }}
                </a-descriptions-item>
                <a-descriptions-item label="订阅折扣" v-if="selectedTeam.subscribeDiscount">
                  {{ (selectedTeam.subscribeDiscount * 10).toFixed(1) }} 折
                </a-descriptions-item>
                <a-descriptions-item label="免费试用" v-if="selectedTeam.trialDays">
                  {{ selectedTeam.trialDays }} 天
                </a-descriptions-item>
              </a-descriptions>
              <div class="team-actions" v-if="userRole === 1">
                <a-button type="primary" @click="startEdit">编辑信息</a-button>
              </div>
            </div>

            <div v-else>
              <a-form :model="teamForm" :rules="teamRules" ref="teamFormRef" :label-col="{ span: 4 }"
                :wrapper-col="{ span: 14 }">
                <a-form-item label="战队名称" name="teamName" required>
                  <a-input v-model:value="teamForm.teamName" />
                </a-form-item>

                <a-form-item label="战队描述" name="description">
                  <a-textarea v-model:value="teamForm.description" rows="3" />
                </a-form-item>

                <a-form-item label="标签" name="tag">
                  <a-input v-model:value="teamForm.tag" />
                </a-form-item>

                <a-form-item label="最大成员数" name="maxCount" required>
                  <a-input-number v-model:value="teamForm.maxCount" :min="currentMemberCount"
                    :placeholder="`当前成员数：${currentMemberCount}`" style="width: 100%" />
                </a-form-item>
                <a-form-item label="订阅价格" name="subscribePrice">
                  <a-input-number v-model:value="teamForm.subscribePrice" :min="0" style="width: 100%" />
                </a-form-item>
                <a-form-item label="订阅周期" name="subscribeCycle">
                  <a-select v-model:value="teamForm.subscribeCycle" allowClear>
                    <a-select-option :value="0">无</a-select-option>
                    <a-select-option :value="1">周</a-select-option>
                    <a-select-option :value="2">月</a-select-option>
                    <a-select-option :value="3">季</a-select-option>
                    <a-select-option :value="4">年</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="订阅折扣" name="subscribeDiscount">
                  <a-input-number v-model:value="teamForm.subscribeDiscount" :min="0" :max="1" :step="0.1"
                    style="width: 100%" :formatter="value => value === 1 ? '无折扣' : `${(value * 10).toFixed(1)} 折`"
                    :parser="value => value === '无折扣' ? 1 : parseFloat(value) / 10" />
                </a-form-item>
                <a-form-item label="免费试用天数" name="trialDays">
                  <a-input-number v-model:value="teamForm.trialDays" :min="0" style="width: 100%" />
                </a-form-item>

                <a-form-item :wrapper-col="{ offset: 4, span: 14 }">
                  <a-space>
                    <a-button type="primary" @click="submitEdit">保存</a-button>
                    <a-button @click="cancelEdit">取消</a-button>
                  </a-space>
                </a-form-item>
              </a-form>
            </div>
          </a-spin>
        </div>

        <!-- 成员列表部分 -->
        <div class="team-members">
          <a-table :columns="memberColumns" :data-source="teamMembers" :loading="membersLoading"
            :pagination="{ pageSize: 10 }" row-key="userId" :key="'member-table-' + teamMembers.length">
            <template #bodyCell="{ column, record }">
              <!-- 头像 -->
              <template v-if="column.key === 'avatar'">
                <a-avatar :src="record.filePath" />
              </template>

              <!-- 用户名 -->
              <template v-else-if="column.key === 'username'">
                {{ record.username }}
              </template>

              <!-- 角色 -->
              <template v-else-if="column.key === 'role'">
                <a-tag :color="record.role === 1 ? 'orange' : 'default'">
                  {{ record.role === 1 ? '队长' : '成员' }}
                </a-tag>
              </template>

              <!-- 状态 -->
              <template v-else-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record.status)">
                  {{ formatStatus(record.status) }}
                </a-tag>
              </template>

              <!-- 加入时间 -->
              <template v-else-if="column.key === 'joinTime'">
                {{ formatDate(record.joinTime) }}
              </template>

              <!-- 加入方式 -->
              <template v-else-if="column.key === 'joinType'">
                {{ formatJoinType(record.joinType) }}
              </template>

              <!-- 邀请人 -->
              <template v-else-if="column.key === 'inviterName'">
                {{ record.inviterName || '无' }}
              </template>

              <!-- 操作 -->
              <template v-else-if="column.key === 'actions'">
                <a-space>
                  <!-- 当前用户显示退出按钮（非队长） -->
                  <a-button danger size="small" v-if="record.userId === currentUserId &&
                    teamMembers.find(m => m.userId === currentUserId)?.role !== 1" @click="handleQuit(record)">
                    退出战队
                  </a-button>

                  <!-- 队长可以操作其他成员 -->
                  <template v-if="teamMembers.find(m => m.userId === currentUserId)?.role === 1 &&
                    record.userId !== currentUserId">
                    <a-button size="small" @click="handlePromote(record)">转让队长</a-button>
                    <a-button danger size="small" @click="handleRemove(record)">移除成员</a-button>
                  </template>
                </a-space>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  findMyTeams,
  findJoinedTeams,
  findCreateTeam,
  findSubscribeTeams,
  getTeamDetails,
  updateTeamDetails,
  getTeamMembers,
  transferTeamLeader,
  removeTeamMember,
  quitTeam
} from '@/api/sysTeamController'




// 当前用户信息
const currentUserId = ref()
const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
currentUserId.value = user.userId || null

// 标签页相关
const activeTab = ref('created')
const createdTeams = ref([])
const joinedTeams = ref([])
const subscribedTeams = ref([])
const loading = ref(false)

// 战队详情相关
const detailVisible = ref(false)
const detailLoading = ref(false)
const selectedTeam = ref(null)
// 校验权限
const userRole = computed(() => {
  if (!selectedTeam.value) return 0;
  // 只检查是否是队长
  const member = teamMembers.value.find(m => m.userId === currentUserId.value);
  return member?.role === 1 ? 1 : 0; // 1=队长，0=普通成员
});

// 编辑战队信息相关
const editing = ref(false)
const teamFormRef = ref(null)
const teamForm = reactive({
  teamName: '',
  description: '',
  tag: '',
  maxCount: null,
  subscribePrice: null,
  subscribeCycle: 0,
  subscribeDiscount: 1,
  trialDays: null
})
const currentMemberCount = ref(0)
const teamRules = {
  teamName: [{ required: true, message: '请输入战队名称', trigger: 'blur' }],
  maxCount: [
    { required: true, message: '请输入最大成员数', trigger: 'change' },
    {
      validator: (_, value) => {
        if (value === null || value === undefined) return Promise.reject('请输入最大成员数')
        if (value < currentMemberCount.value) {
          return Promise.reject(new Error(`最大成员数不能小于当前成员数：${currentMemberCount.value}`))
        }
        return Promise.resolve()
      },
      trigger: 'change',
    },
  ],
  subscribePrice: [
    {
      validator: (_, value) => {
        if (teamForm.subscribeCycle > 0 && (!value || value <= 0)) {
          return Promise.reject('请设置有效的订阅价格')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  subscribeDiscount: [
    {
      validator: (_, value) => {
        if (value < 0 || value > 1) {
          return Promise.reject('折扣必须在0-1之间')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 成员列表相关
const teamMembers = ref([])
const membersLoading = ref(false)
const memberColumns = [
  { title: '头像', dataIndex: 'filePath', key: 'avatar', width: 64 },
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '角色', key: 'role' },
  { title: '状态', key: 'status' },
  { title: '加入时间', dataIndex: 'joinTime', key: 'joinTime' },
  { title: '加入方式', key: 'joinType' },
  { title: '邀请人', dataIndex: 'inviterName', key: 'inviterName' },
  { title: '操作', key: 'actions' }
]

// 添加订阅周期格式化函数
const formatCycle = (cycle) => {
  switch (cycle) {
    case 1: return '周'
    case 2: return '月'
    case 3: return '季'
    case 4: return '年'
    default: return '未知周期'
  }
}

// 在模板或计算属性中
const emptyTextMap = {
  created: '您尚未创建或管理任何战队',
  joined: '您尚未加入任何战队',
  subscribed: '您尚未订阅任何战队'
}

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  return new Date(dateString).toLocaleString()
}

const getStatusColor = (status) => {
  return { 0: 'green', 1: 'orange', 2: 'red', 3: 'default', 4: 'purple' }[status] || 'default'
}

const formatStatus = (status) => {
  return { 0: '正常', 1: '待审核', 2: '已拒绝', 3: '已退出', 4: '已禁言' }[status] || '未知'
}

const formatJoinType = (type) => {
  switch (type) {
    case 0: return '主动加入'
    case 1: return '邀请加入'
    default: return '未知方式'
  }
}

// 初始化加载战队列表
const fetchTeams = async () => {
  loading.value = true
  try {
    // 分别调用两个接口
    const [createdRes, captainRes, joinedRes, subscribedRes] = await Promise.all([
      findCreateTeam(),    // 查询创建的战队
      findMyTeams(),       // 查询作为队长的战队
      findJoinedTeams(),
      findSubscribeTeams(),
    ])

    // 合并创建的战队和作为队长的战队（去重）
    const createdTeamIds = new Set(createdRes?.data?.data?.map(t => t.id));
    const createdTeamsData = (createdRes?.data?.data || []).map(t => ({ ...t, isCaptain: false }));
    const captainTeamsData = (captainRes?.data?.data || [])
      .filter(t => !createdTeamIds.has(t.id))
      .map(t => ({ ...t, isCaptain: true }));

    // 队长战队在前
    createdTeams.value = [...captainTeamsData, ...createdTeamsData];
    joinedTeams.value = joinedRes?.data?.data || [];
    subscribedTeams.value = subscribedRes?.data?.data || [];
  } catch (e) {
    message.error('获取战队数据失败')
  } finally {
    loading.value = false
  }
}

// 加载战队详情
const loadTeamDetails = async () => {
  if (!selectedTeam.value?.teamId) return
  detailLoading.value = true
  try {
    const res = await getTeamDetails({ teamId: selectedTeam.value.teamId })
    Object.assign(selectedTeam.value, res.data)

    // 同步表单数据，包括订阅字段
    Object.assign(teamForm, {
      teamName: selectedTeam.value.teamName || '',
      description: selectedTeam.value.description || '',
      tag: selectedTeam.value.tag || '',
      maxCount: selectedTeam.value.maxCount || 0,
      subscribePrice: selectedTeam.value.subscribePrice || 0,
      subscribeCycle: selectedTeam.value.subscribeCycle || 0,
      subscribeDiscount: selectedTeam.value.subscribeDiscount || 1,
      trialDays: selectedTeam.value.trialDays || 0
    })
  } catch (err) {
    message.error('加载战队详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 加载成员列表
const fetchMembers = async () => {
  if (!selectedTeam.value?.teamId) return
  membersLoading.value = true
  try {
    const res = await getTeamMembers({ teamId: selectedTeam.value.teamId })
    teamMembers.value = res.data?.data || []
    currentMemberCount.value = teamMembers.value.length
  } catch (e) {
    message.error('获取成员失败')
  } finally {
    membersLoading.value = false
  }
}

// 标签页切换
const onTabChange = (key) => {
  activeTab.value = key
}

// 打开战队详情
const openDetail = (team) => {
  selectedTeam.value = {
    ...team,
    teamId: team.id || team.teamId // 兼容不同字段名
  }
  detailVisible.value = true

  // 加载详情和成员
  loadTeamDetails()
  fetchMembers()
}

// 关闭详情
const closeDetail = () => {
  detailVisible.value = false
  selectedTeam.value = null
  editing.value = false
}

// 编辑战队信息
const startEdit = async () => {
  editing.value = true
}


const cancelEdit = () => {
  editing.value = false
  // 回滚表单数据
  Object.assign(teamForm, {
    teamName: selectedTeam.value.teamName,
    description: selectedTeam.value.description,
    tag: selectedTeam.value.tag,
    maxCount: selectedTeam.value.maxCount,
  })
}

const submitEdit = async () => {
  try {
    await teamFormRef.value.validate();
    const response = await updateTeamDetails(
      { teamId: selectedTeam.value.teamId },
      { ...teamForm }
    );
    message.success('战队信息更新成功');
    editing.value = false;

    // 方法1：直接更新 selectedTeam（快速响应）
    Object.assign(selectedTeam.value, teamForm);

    // 方法2：重新从后端拉取最新数据（确保一致性）
    await loadTeamDetails();
  } catch (error) {
    console.error('更新失败:', error);
    message.error(error.response?.data?.message || '更新失败，请检查数据');
  }
};

// 成员管理
const handlePromote = async (member) => {
  Modal.confirm({
    title: '确认转让队长',
    content: `确定将队长权限转让给 ${member.username} 吗？`,
    onOk: async () => {
      try {
        await transferTeamLeader({
          teamId: selectedTeam.value.teamId,
          newLeaderId: member.userId
        });
        message.success('队长已转让');

        // 关键修复：强制刷新成员列表和战队详情
        await Promise.all([
          fetchTeams(),       // 必须刷新战队列表
          fetchMembers(),      // 刷新成员列表
          loadTeamDetails()   // 刷新当前战队详情
        ]);

        // 更新当前用户的角色状态
        const currentMember = teamMembers.value.find(m => m.userId === currentUserId.value);
        userRole.value = currentMember?.role || 0;
      } catch (error) {
        message.error(error.response?.data?.message || '操作失败');
      }
    }
  });
};

const handleRemove = (member) => {
  Modal.confirm({
    title: '确认移除成员',
    content: `确定要将 ${member.username} 移出战队吗？`,
    okType: 'danger',
    onOk: async () => {
      try {
        await removeTeamMember({ teamId: selectedTeam.value.teamId, memberId: member.userId })
        message.success('成员已移除')

        await fetchMembers()
        // 更新当前成员数
        currentMemberCount.value = teamMembers.value.length
      } catch {
        message.error('移除失败')
      }
    }
  })
}

const handleQuit = (member) => {
  Modal.confirm({
    title: '退出战队',
    content: '确认退出当前战队？',
    okType: 'danger',
    onOk: async () => {
      try {
        await quitTeam({ teamId: selectedTeam.value.teamId })
        message.success('退出成功')
        detailVisible.value = false
        // 刷新战队列表
        await fetchTeams()
      } catch {
        message.error('退出失败')
      }
    }
  })
}

// 初始化加载
onMounted(fetchTeams)
</script>

<style scoped>
.my-team-container {
  padding: 16px;
}

.team-detail {
  padding: 16px;
}

.team-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
}

.team-members {
  padding: 16px;
  margin-top: 24px;
  border-top: 1px solid #f0f0f0;
}
</style>
